package org.niux.aims.dao.impl;

import java.util.List;
import java.util.logging.Level;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.niux.aims.dao.ILogsDAO;
import org.niux.aims.models.EntityManagerHelper;
import org.niux.aims.models.Logs;
import org.springframework.stereotype.Repository;

/**
 * 
 * Copyright (c) 2009,niux<br>
 * All rights reserved.<br>
 * 
 * 文件名称：LogsDAO.java<br>
 * 摘    要：日志数据操作类<br>
 * <br>
 * 当前版本：<br>
 * 作    者：铭显 Email: <a href="mailto:liangmingxian@gmail.com">liangmingxian@gmail.com</a><br>
 * 完成日期：@since 2013-7-30<br>
 * <br>
 * 取代版本：<br>
 * 原作者  ：<br>
 * 完成日期：@since Oct 22, 2009<br>
 */
@Repository(value="logsDao")
public class LogsDAO implements ILogsDAO {
	// property constants
	public static final String LOG = "log";

	private EntityManager getEntityManager() {
		return EntityManagerHelper.getEntityManager();
	}

	/**
	 * 
	 * 方法概述：添加日志
	 * 描述：添加日志
	 * @param entity
	 * 返回类型：void
	 * 修改人：梁铭显 
	 * 修改时间：2013-9-25
	 */
	public void save(Logs entity) {
		try {
			getEntityManager().getTransaction().begin();
			getEntityManager().persist(entity);
			getEntityManager().getTransaction().commit();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	/**
	 * Delete a persistent Logs entity. This operation must be performed within
	 * the a database transaction context for the entity's data to be
	 * permanently deleted from the persistence store, i.e., database. This
	 * method uses the {@link javax.persistence.EntityManager#remove(Object)
	 * EntityManager#delete} operation.
	 * 
	 * <pre>
	 * EntityManagerHelper.beginTransaction();
	 * LogsDAO.delete(entity);
	 * EntityManagerHelper.commit();
	 * entity = null;
	 * </pre>
	 * 
	 * @param entity
	 *            Logs entity to delete
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void delete(Logs entity) {
		EntityManagerHelper.log("deleting Logs instance", Level.INFO, null);
		try {
			entity = getEntityManager()
					.getReference(Logs.class, entity.getId());
			getEntityManager().remove(entity);
			EntityManagerHelper.log("delete successful", Level.INFO, null);
		} catch (RuntimeException re) {
			EntityManagerHelper.log("delete failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * Persist a previously saved Logs entity and return it or a copy of it to
	 * the sender. A copy of the Logs entity parameter is returned when the JPA
	 * persistence mechanism has not previously been tracking the updated
	 * entity. This operation must be performed within the a database
	 * transaction context for the entity's data to be permanently saved to the
	 * persistence store, i.e., database. This method uses the
	 * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge}
	 * operation.
	 * 
	 * <pre>
	 * EntityManagerHelper.beginTransaction();
	 * entity = LogsDAO.update(entity);
	 * EntityManagerHelper.commit();
	 * </pre>
	 * 
	 * @param entity
	 *            Logs entity to update
	 * @return Logs the persisted Logs entity instance, may not be the same
	 * @throws RuntimeException
	 *             if the operation fails
	 */
	public Logs update(Logs entity) {
		EntityManagerHelper.log("updating Logs instance", Level.INFO, null);
		try {
			Logs result = getEntityManager().merge(entity);
			EntityManagerHelper.log("update successful", Level.INFO, null);
			return result;
		} catch (RuntimeException re) {
			EntityManagerHelper.log("update failed", Level.SEVERE, re);
			throw re;
		}
	}

	public Logs findById(Integer id) {
		EntityManagerHelper.log("finding Logs instance with id: " + id,
				Level.INFO, null);
		try {
			Logs instance = getEntityManager().find(Logs.class, id);
			return instance;
		} catch (RuntimeException re) {
			EntityManagerHelper.log("find failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * Find all Logs entities with a specific property value.
	 * 
	 * @param propertyName
	 *            the name of the Logs property to query
	 * @param value
	 *            the property value to match
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            number of results to return.
	 * @return List<Logs> found by query
	 */
	@SuppressWarnings("unchecked")
	public List<Logs> findByProperty(String propertyName, final Object value,
			final int... rowStartIdxAndCount) {
		EntityManagerHelper.log("finding Logs instance with property: "
				+ propertyName + ", value: " + value, Level.INFO, null);
		try {
			final String queryString = "select model from Logs model where model."
					+ propertyName + "= :propertyValue";
			Query query = getEntityManager().createQuery(queryString);
			query.setParameter("propertyValue", value);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			EntityManagerHelper.log("find by property name failed",
					Level.SEVERE, re);
			throw re;
		}
	}

	public List<Logs> findByLog(Object log, int... rowStartIdxAndCount) {
		return findByProperty(LOG, log, rowStartIdxAndCount);
	}

	/**
	 * Find all Logs entities.
	 * 
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            count of results to return.
	 * @return List<Logs> all Logs entities
	 */
	@SuppressWarnings("unchecked")
	public List<Logs> findAll(final int... rowStartIdxAndCount) {
		EntityManagerHelper.log("finding all Logs instances", Level.INFO, null);
		try {
			final String queryString = "select model from Logs model";
			Query query = getEntityManager().createQuery(queryString);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			EntityManagerHelper.log("find all failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * 
	 * 方法概述：分页获取日志数据
	 * 描述：分页获取日志数据
	 * @param startPage
	 * @param pageSize
	 * @return
	 * 返回类型：List<Logs>
	 * 修改人：梁铭显 
	 * 修改时间：2013-9-25
	 */
	@SuppressWarnings("unchecked")
	public List<Logs> findByPage(int startPage, int pageSize){
		StringBuffer hql = new StringBuffer();
		
		hql.append("SELECT logs ");
		hql.append("FROM Logs logs ");
		hql.append("WHERE 1=1 ");
		hql.append("ORDER BY logs.id DESC");
		
		Query query = getEntityManager().createQuery(hql.toString());
		
		query.setFirstResult(startPage);
		query.setMaxResults(pageSize);
		
		return query.getResultList();
	}
	
	/**
	 * 
	 * 方法概述：删除所有日志
	 * 描述：删除所有日志
	 * 返回类型：void
	 * 修改人：梁铭显 
	 * 修改时间：2013-9-25
	 */
	public void removeAll(){
		StringBuffer hql = new StringBuffer();
		
		hql.append("DELETE Logs logs ");
		hql.append("WHERE 1=1 ");
		
		Query query = getEntityManager().createQuery(hql.toString());
		
		getEntityManager().getTransaction().begin();
		query.executeUpdate();
		getEntityManager().getTransaction().commit();
	}
}